/**
 * Copyright (C) 2013-2014 the original author or authors.
 */
package com.foreveross.bsl.push.web;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;

import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.foreveross.bsl.common.utils.web.QuerySpecs;
import com.foreveross.bsl.common.utils.web.model.PageMustache;
import com.foreveross.bsl.common.utils.web.model.QueryModelHelper;
import com.foreveross.bsl.common.utils.web.model.SelectBoxModel;
import com.foreveross.bsl.common.utils.web.model.SortInfoModel;
import com.foreveross.bsl.push.application.PushMgmtService;
import com.foreveross.bsl.push.application.vo.PushVo;
import com.foreveross.bsl.push.web.AppIdKeyHelper.AppIdKeyPair;

/**
 * xxx
 *
 * @author Wangyi
 * @version v1.0
 *
 * @date 2013-9-23
 *
 */
@Controller
@RequestMapping(value = "/push")
public class PushQueryController extends PushBaseController {
	
	@Inject
	private PushMgmtService pushMgmtService;

	@Inject
	private AppIdKeyHelper appIdKeyHelper;
	
	@RequestMapping(value = "list-pushs/{requestId}")
	public String listPushs(@RequestParam(value = "page", defaultValue = "1") int pageNumber,
			@RequestParam(value = "page.size", defaultValue = PAGE_SIZE) int pageSize,
			@PathVariable("requestId") String requestId,
			@RequestParam(value="appKey", required=false) String appKey,
			@RequestParam(value="appId", required=false) String appId,
			Model model, HttpServletRequest request) {
		
		String queryUrl="/push/list-pushs/"+requestId;
		QueryModelHelper queryHelper=new QueryModelHelper(queryUrl, makeQueryFields(), makeSortInfo());
		QuerySpecs querySpecs=queryHelper.populateQueryModel(model, request);
		
		Page<PushVo> pushs = pushMgmtService.findPushsByRequest(requestId, pageNumber, pageSize, querySpecs);
		model.addAttribute("pushs", pushs);
		model.addAttribute("page", new PageMustache(pushs, PAGINATION_SIZE));

		AppIdKeyPair pair=appIdKeyHelper.check(appId, appKey, false);
		model.addAttribute("appId", pair.getAppId());
		model.addAttribute("appKey", pair.getAppKey());
		model.addAttribute("requestId", requestId);

		return "push/push-list";
	}
	
	private final SelectBoxModel makeQueryFields(){
		SelectBoxModel sbm=new SelectBoxModel();
		sbm.addOption("LIKE_target.deviceId", "设备ID", true);
		sbm.addOption("EQ_target.alias", "用户名");
		sbm.addOption("EQ_status", "推送状态");
		return sbm;
	}
	
	private final SortInfoModel makeSortInfo(){
		SortInfoModel sim=new SortInfoModel();
		sim.setSortEntry("create_time", "创建时间", false);
		sim.setSortEntry("target.alias", "用户名", true);
		return sim;
	}
	
}
